package edu.hz.service.impl;

import edu.hz.dao.NewsCommentsMapper;
import edu.hz.dao.NewsMapper;
import edu.hz.dao.UserMapper;
import edu.hz.model.dto.NewsCommentDto;
import edu.hz.model.entity.NewsCommentEntity;
import edu.hz.model.entity.NewsEntity;
import edu.hz.model.entity.UserEntity;
import edu.hz.service.NewsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {

    @Resource
    NewsMapper newsMapper;

    @Resource
    NewsCommentsMapper newsCommentsMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public List<NewsEntity> getAllNews() {
        return newsMapper.getAllNews();
    }

    @Override
    public NewsEntity selectById(Integer id) {
        return newsMapper.selectById(id);
    }

    @Override
    public List<NewsCommentDto> getCommentsByNewsId(Integer id) {
        List<NewsCommentEntity> comments = newsCommentsMapper.selectByNewsId(id);
        List<NewsCommentDto> retList = new ArrayList<>();
        comments.forEach(c -> {
            NewsCommentDto dto = new NewsCommentDto();
            UserEntity user = userMapper.selectById(c.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setContent(c.getContent());
                dto.setSendTime(c.getCommentTime());
                retList.add(dto);
            }
        });
        return retList;
    }
}
